<?php
/**
 * Created by PhpStorm.
 * User: syzhou
 * Date: 2020-11-12
 * Time: 14:06
 */

require_once __DIR__ . '/common.php';

/**
 * @var PDO
 */
global $srcPDO;

/**
 * @var PDO
 */
global $dstPDO;

$srcTable = 'applications';
$dstTable = $srcTable;
$srcProjectIds = getSrcProjectIds();
$srcProjectIdRangeStr = '(' . implode(',', $srcProjectIds) . ')';
$fetchedSrcTableFields = [
    'id', 'project_name', 'status_id', 'user_id', 'award_id', 'prof_category', 'applicant_editable', 'created_at',
    'updated_at', 'submitted_at', 'attachment_processed', 'large_group_id',
];
$fetchedSrcTableFieldsStr = implode(', ', $fetchedSrcTableFields);
$selectSrcRecordsStmt = $srcPDO->query("select $fetchedSrcTableFieldsStr from $srcTable where id in $srcProjectIdRangeStr", PDO::FETCH_ASSOC);
$srcRecords = $selectSrcRecordsStmt->fetchAll();
$selectSrcRecordsStmt->closeCursor();

$insertedDstTableFields = $fetchedSrcTableFields;
$insertedDstTableFieldsStr = implode(', ', $insertedDstTableFields);
$insertedDstTableValuePlaceholders = array_map(function($fieldName) {
    return ":$fieldName";
}, $insertedDstTableFields);
$insertedDstTableValuePlaceholdersStr = implode(', ', $insertedDstTableValuePlaceholders);
$insertDstRecordsStmt = $dstPDO->prepare("insert into $dstTable ($insertedDstTableFieldsStr) values ($insertedDstTableValuePlaceholdersStr)");
foreach ($srcRecords as $srcRecord) {
    $srcRecordId = $srcRecord['id'];
    echo "transfer project #$srcRecordId...\n";
    $dstRecord = $srcRecord;
    $dstRecord['status_id'] = 'B2';
    $values = [];
    foreach ($insertedDstTableFields as $field) {
        $valuePlaceholder = ":$field";
        $values[$valuePlaceholder] = $dstRecord[$field];
    }
    $insertDstRecordsStmt->execute($values);
}
